<?php
/**
 * @file fashionwear.php
 * @author LinLin
 * @date 2016年11月22日 上午10:27:00
 * @brief 
 */
namespace haibao\cms\business\fashionwear;

use haibao\cms\data\fashionwear\fashionwear as FashionWearData;
use haibao\cms\data\fashionwear\FashionWearProduct as FashionWearProductData;
use haibao\cms\business\BusinessException;
use haibao\frame\data\query\Condition;
use haibao\cms\web\view\app\article\Preview;
use haibao\cms\data\fashionwear\FashionWearProperty as FashionWearPropertyData;
use haibao\cms\data\fashionwear\FashionWearProperty;

class FashionWear extends \haibao\cms\business\Base{
    
    public static function getNewFashionWear(){
        $data = new \haibao\cms\data\fashionwear\FashionWear();
        return $data->getNewFashionWear();
    }
    
    public static function getNearCurrentId($currentId,$starId){
        $data = new \haibao\cms\data\fashionwear\FashionWear();
        return $data->getNearCurrentId($currentId,$starId);
    }
    
    public static function getOneFashionWearByStarId($starId){
        $data = new \haibao\cms\data\fashionwear\FashionWear();
        return $data->getOneFashionWearByStarId($starId);
    }
    
    /**
     * 时尚搭配合并图片
     * @param unknown $fashionwearid 时尚穿搭id
     */
    public static function combineFashionWearPic($fashionwearid){
        //取对应productid
        $data = new \haibao\cms\data\fashionwear\FashionWear();
        $productIds = $data->combineFashionWearPic($fashionwearid);
        $leftImage = $productInfo = $productId = array();
        //取对应的productinfo
        if($productIds){
            foreach($productIds as $k=>$v){
                $productId[] = $k;
            }
            $idStr = implode(',',$productId);
            //$productInfo = \haibao\cms\business\Product::getProductInfoByIds($idStr);
            $productInfo = \haibao\cms\business\newproduct\Goods::getGoodsInfoByIds($idStr);

            $brandIds = $brandInfo = array();
            foreach($productInfo as $key=>$val){
                $brandIds[] = $val['BrandId'];
            }
            if($brandIds){
                $brandInfo = \haibao\cms\business\Brand::getBrandByIds($brandIds,false,true);
                foreach($productInfo as $k=>$v){
                    if(isset($brandInfo[$v['BrandId']])){
                        $productInfo[$k]['Description'] = isset($brandInfo[$v['BrandId']]->NameEN) ? $brandInfo[$v['BrandId']]->NameEN : $brandInfo[$v['BrandId']]->NameCN;
                    }
                    if(isset($productIds[$v['Id']])){
                        $productInfo[$k]['ProductOrder'] = $productIds[$v['Id']];
                    }
                }
                
                $order = array();
                foreach ($productInfo as $vv) {
                    $order[] = $vv['ProductOrder'];
                }
                array_multisort($order, SORT_ASC, $productInfo);
            }
            //取左侧图片信息
            $fashionWearInfo = self::getOneFashionWearById($fashionwearid);
            $leftImage = \haibao\cms\business\ImageLibrary::getImageById($fashionWearInfo->ImageId);
            $leftImage = $leftImage->Filename;
            //返回picurl
        }
        return array($leftImage,$productInfo);
    }
    
    /**
     * 通过时尚穿搭ID获取时尚穿搭信息
     * @param unknown $fashionwearid
     * @return NULL
     */
    public static function getOneFashionWearById($fashionwearid){
        $data = new \haibao\cms\data\fashionwear\FashionWear();
        return $data->getOneFashionWearById($fashionwearid);
    }
    
    /**
     * 更改时尚穿搭图片状态（删除）
     * 在时尚穿搭表中 更改图片状态   在imagelibrary表中更改 IsFashionWear状态
     * @param unknown $id 图片id
     * @param unknown $status 状态
     * @throws BusinessException
     */
    public static function updateImageStatus($id,$imageId, $status = \haibao\cms\model\data\fashionwear\FashionWear::STATUS_DELETE){
        if(!isset($id)){
            throw new BusinessException('图片ID不能为空');
        }
    
        $data = new \haibao\cms\data\fashionwear\FashionWear();
        $data->updateImageStatus($id,$imageId, $status, self::getCurrentUser()->UserName);
    
        //self::saveOperateHistory(self::FUNC_CODE_FASHION_WEAR_DELETE, array($id, $status));
    }
    
    /**
     * 保存时尚穿搭主表信息
     * @param unknown $model
     */
    public static function saveFashionWear($model,$productId){
        if(!$model->PublishTime){
            throw new BusinessException('发布时间不能为空');
        }
        if(!$model->StarId && !$model->UserDefinedStarName){
            throw new BusinessException('明星不能为空');
        }
        if(empty($productId)){
            throw new BusinessException('请添加单品');
        }
        if($model->UserDefinedStarName){
            $model->StarId = '';
        }
        //self::checkOperation(self::FUNC_CODE_FASHION_WEAR_EDIT);
        if($model->Id){
            $data = new FashionWearData();
            $fashionWearInfo = $data->getOneById($model->Id);
            $model->Editor = $fashionWearInfo->Editor;
            $model->CreateBy =  $fashionWearInfo->CreateBy;
            $model->CreateTime =$fashionWearInfo->CreateTime;
        }else{
            $model->Editor = self::getCurrentUser()->RealName;
            $model->CreateBy = self::getCurrentUser()->Id;
            $model->CreateTime = new \DateTime();
        }
        $model->UpdateTime = new \DateTime();
        $data = new FashionWearData();
        return $data->saveFashionWear($model);
        //self::saveOperateHistory(self::FUNC_CODE_FASHION_WEAR_EDIT, $model->toArray(true,true));
    }
    
    /**
     * 保存时尚穿搭product表信息
     * @param unknown $fashionwearid 时尚穿搭id 
     * @param unknown $productModel 对应的单品信息实体
     * @throws BusinessException
     */
     
   public static function saveFashionWearProduct($fashionwearid,$productModel){
       //self::checkOperation(self::FUNC_CODE_FASHION_WEAR_EDIT);
       if($productModel && $productModel[0]){
           $isProductIdNull = false;
           foreach($productModel as $key=>$val){
               if($val->BrandId == ''){
                   $isProductIdNull = true;
               }
               if(!empty($val->ProductName) && mb_strlen($val->ProductName,'utf-8') > 10){
                  $errorStr = $key + 1;
                  throw new BusinessException('第'.$errorStr.'个手填单品名不能超过10个字符');
               }
               if($val->BrandId == ''){
                   $productModel[$key]->BrandCNname = '';
                   $productModel[$key]->BrandENname = '';
                   $productModel[$key]->BrandSpaceId = '';
               }
               if(empty($val->ProductId) && empty($val->ProductName)){
                   throw new BusinessException('单品名不能为空');
               }
               if(!empty($val->ProductId) && empty($val->BrandId)){
                   throw new BusinessException('品牌不能为空');
               }
               if(!empty($val->ProductId) && empty($val->ProductName) && $val->IsShowProductName == 1){
                   $productModel[$key]->IsShowProductName = 0;
               }
               if(empty($val->ProductId) && empty($val->BrandId)){
                   $productModel[$key]->IsShowProductName = 1;
               }
           }
       }
       $data = new FashionWearProductData();
       return $data->saveFashionWearProduct($fashionwearid,$productModel);
      // self::saveOperateHistory(self::FUNC_CODE_FASHION_WEAR_EDIT, $productModel->toArray(true,true));
   }
   
   /**
    * 通过图片id数组获得时尚穿搭 关联明星及关联单品 的信息
    * @param unknown $imageIds 图片数组
    */
   public static function getFashionProductInfoByImgIds($imageIds){
       $data = new FashionWearData();
       return $data->getFashionProductInfoByImgIds($imageIds);
   }
   
   /**
    * 通过图片ID数组 获得分享图片（sharepicurl）地址
    * @param unknown $imageIds
    */
   public static function getSharePicUrlByImgIds($imageIds){
       $data = new FashionWearData();
       return $data->getSharePicUrlByImgIds($imageIds);
   }
   
   /**
    * 通过图片ID获得时尚穿搭主表信息
    * @param unknown $imageId
    */
   public static function getOneFashionWearByImgId($imageId,$isPublished = false){
       $data = new FashionWearData();
       return $data->getOneFashionWearByImgId($imageId,$isPublished);
   }
   
   /**
    * All 通过实体获得时尚穿搭产品信息
    * @param unknown $query
    */
   public static function getFashionWearProductByFilter($query){
       $data = new FashionWearProductData();
       return $data->getFashionWearProductByFilter($query);
   }
     
   /**
    * 通过时尚穿搭ID获得关联单品的排序信息
    * @param unknown $fashionWearId
    */
   public static function getOneFashionWearProductByFashionId($fashionWearId){
       $data = new FashionWearProductData();
       return $data->getOneFashionWearProductByFashionId($fashionWearId);
   }
   
   /**
    * 通过图片ID获得已经发布的时尚穿搭信息
    * @param unknown $imageId
    */
   public static function getOneHasPublishFashionWear($imageId){
       $data = new FashionWearData();
       return $data->getOneHasPublishFashionWear($imageId);
   }
   
   /**
    * All 通过实体获得时尚穿搭主表信息
    * @param unknown $query
    * @return multitype:
    */
   public static function getFashionWearByFilter($query){
       $data = new FashionWearData();
       return $data->getFashionWearByFilter($query);
   }
   
   /**
    * 更新sharepicurl
    */
   public static function updateSharePicUrlByFashionWearId($fashionwearid,$sharePicUrl){
       $data = new FashionWearData();
       return $data->updateSharePicUrlByFashionWearId($fashionwearid,$sharePicUrl);
   }
   
   /**
    * 增加时尚穿搭评论数
    */
   public static function updateCommentNum($fashionWearId,$num=1,$isSub=false){
   	if(!$fashionWearId){
   		throw new \haibao\cms\business\BusinessException('Id不能为空');
   	}
   	$data = new FashionWearPropertyData();
   	$data->updateCommentNum((int)$fashionWearId,$num,$isSub);
   }
   
   /**
    * 获取数据
    */
   public static function getCommentNum($fashionWearPropertyFilter){
   	$data = new \haibao\cms\data\fashionwear\FashionWearProperty();
   	return $data->getOne($fashionWearPropertyFilter);
   }

    public static function addClickNum($fashionId){
        $data = new \haibao\cms\data\fashionwear\FashionWearProperty();
        return $data->addClickNum($fashionId);
    }

    public static function getOneByFilter($filter){
        $data = new \haibao\cms\data\fashionwear\FashionWear();
        return $data->getOne($filter);
    }
   
    
    
    //search data
    public static function searchImageData($name,$skip,$limit){
        $result = array();
        $resultCount = 0;
         
        $total = $skip + $limit;
        if ($total > 1000){
            if ($skip >= 1000){
                $skip = 1000;
                return array($result,$resultCount);
            } else {
                $limit = 1000 - $skip;
            }
        }
         
        $fashionWearFilter = new \haibao\cms\model\filter\fashionwear\FashionWear();
        $fashionWearFilter->select(array(
            $fashionWearFilter::CONDITION_FIELD_NAME_ID,
            $fashionWearFilter::CONDITION_FIELD_NAME_IMAGEID,
            $fashionWearFilter::CONDITION_FIELD_NAME_UPDATETIME,
            $fashionWearFilter::CONDITION_FIELD_NAME_TITLE
        ));
         
        $fashionWearFilter->limit($skip,$limit);
        $fashionWearFilter->order($fashionWearFilter::CONDITION_FIELD_NAME_UPDATETIME,false);
         
        $fashionWearFilter->where($fashionWearFilter::CONDITION_FIELD_NAME_STATUS,Condition::CONDITION_EQUAL,\haibao\cms\model\data\fashionwear\FashionWear::STATUS_ENABLE);
        $fashionWearFilter->where($fashionWearFilter::CONDITION_FIELD_NAME_PUBLISHED,Condition::CONDITION_EQUAL,\haibao\cms\model\data\fashionwear\FashionWear::PUBLISHED_YES);
         
        $imageFilter = new \haibao\cms\model\filter\ImageLibrary();
        $imageFilter->select(array(
            $imageFilter::CONDITION_FIELD_NAME_ID,
            $imageFilter::CONDITION_FIELD_NAME_FILENAME,
            $imageFilter::CONDITION_FIELD_NAME_WIDTH,
            $imageFilter::CONDITION_FIELD_NAME_HEIGHT,
            $imageFilter::CONDITION_FIELD_NAME_SOURCE,
            $imageFilter::CONDITION_FIELD_NAME_DESCRIPTION,
            $imageFilter::CONDITION_FIELD_NAME_CREATEBY,
            $imageFilter::CONDITION_FIELD_NAME_CREATETIME,
            $imageFilter::CONDITION_FIELD_NAME_STATUS,
            $imageFilter::CONDITION_FIELD_NAME_SIZE,
            $imageFilter::CONDITION_FIELD_NAME_LEVEL,
            $imageFilter::CONDITION_FIELD_NAME_IS_FASHION_WEAR,
        ));
    
        $fashionWearFilter->leftJoin($imageFilter,null,$fashionWearFilter::CONDITION_FIELD_NAME_IMAGEID,$imageFilter::CONDITION_FIELD_NAME_ID,$fashionWearFilter::CONDITION_FIELD_NAME_RELATED_INFO,false);

        $resultCount = self::getCountFashionWear();
        $result = self::getFashionWearByFilter($fashionWearFilter);
         
        if($result){
            foreach($result as $key=>$val){
                $sourceId[] = $val->RelatedInfo->Source;
            }
            $sourceInfo = self::getSourceNameByIds($sourceId);
            foreach($result as $key=>$val){
                if(isset($sourceInfo[$val->RelatedInfo->Source])){
                    $result[$key]->RelatedInfo->SourceName = $sourceInfo[$val->RelatedInfo->Source];
                }
            }
        }
        //$result = \haibao\cms\business\ImageLibrary::getImageAllByFilter($imageFilter);
        return array($result,$resultCount);
    }
     
    public static function getSourceNameByIds($sourceId){
        $data = new \haibao\cms\data\ImageLibrary();
        return $data->getSourceNameByIds($sourceId);
    }
     
    public static function getCountFashionWear(){
        $data = new FashionWearData();
        return $data->getCountFashionWear();
    }
     
    public static function formatImageList($result,$line,$normalOptions,$specialOptions = array()){
        $data = $array = $ids = array();
        $count = 0;
    
        foreach ($result as $value){
            $arr = $value->toArray();
            $arr['SourceName'] = $value->RelatedInfo->SourceName;
            $arr['Width'] = $value->RelatedInfo->Width;
            $arr['Height'] = $value->RelatedInfo->Height;
            $arr['Filename'] = $value->RelatedInfo->Filename;
            $arr['Description'] = $value->RelatedInfo->Description;
            array_push($array,$arr);
        }
         
        $row = array();
        $imgLengthNormal = $imgLengthMax =  0;
        foreach ($array as $key=>$value){
            list($screenWidth,$normalHeight,$maxHeight,$padding) = self::getLineOption(count($data) + 1,$normalOptions,$specialOptions);
            //高度一定的情况下 等比例算这张图片的宽度
            //width/height = x/maxheight
            $value['Width'.$maxHeight] = $value['Height'] > $maxHeight ? round($value['Width']*$maxHeight/$value['Height']) : $value['Width'];
            $value['Width'.$normalHeight] = $value['Height'] > $normalHeight ? round($value['Width']*$normalHeight/$value['Height']) : $value['Width'];
            $length = $imgLengthNormal + count($row)*$padding + $value['Width'.$normalHeight];
            if ($length == $screenWidth){
                array_push($row,$value);
                 
                foreach ($row as $k=>$v){
                    $row[$k]['TargetWidth'] = $v['Width'.$normalHeight];
                    $row[$k]['TargetHeight'] = $v['Height'] > $normalHeight ? $normalHeight : $v['Height'];
                    $row[$k]['ContainerHeight'] = $normalHeight;
                }
                 
                self::storeRow($data,$row,$padding,$screenWidth);
                 
                if (count($data) == $line){
                    break;
                }
                 
                $imgLengthNormal = $imgLengthMax = 0;
                $row = array();
            } else if ($length < $screenWidth) {
                array_push($row,$value);
                $imgLengthNormal += $value['Width'.$normalHeight];
                $imgLengthMax += $value['Width'.$maxHeight];
                if ($key == count($array) - 1){
                    if (count($data) < $line){
                        //不够10行，最后一行仍然出
                        $needLarge = false;
                        $remainLength = $screenWidth - (count($row) - 1) * $padding;
                        $height = $normalHeight;
                        if ($imgLengthMax >= $remainLength){
                            $needLarge = true;
                            $height = round($maxHeight*$remainLength/$imgLengthMax);
                        }
                         
                        foreach ($row as $k=>$v){
                            if ($needLarge){
                                $row[$k]['TargetWidth'] = round($v['Width'.$maxHeight]*$remainLength/$imgLengthMax);
                            } else {
                                $row[$k]['TargetWidth'] = $v['Width'.$normalHeight];
                            }
    
                            $row[$k]['TargetHeight'] = $v['Height'] > $height ? $height : $v['Height'];
                            $row[$k]['ContainerHeight'] = $height;
                        }
                         
                        self::storeRow($data,$row,$padding,$screenWidth);
                    }
                } else {
                    continue;
                }
            } else {
                $remainLength = 0;
                if (count($row) == 0){
                    $remainLength = $screenWidth;
                } else {
                    $remainLength = $screenWidth - (count($row) - 1) * $padding;
                }
                if ($imgLengthMax > $remainLength){
                    //最大尺存高缩小
                    $ratio = $remainLength/$imgLengthMax;
                    $height = floor($maxHeight*$ratio);
    
                    foreach ($row as $k=>$v){
                        $row[$k]['TargetWidth'] = round($v['Width'.$maxHeight]*$ratio);
                        $row[$k]['TargetHeight'] = $v['Height'] > $height ? $height : $v['Height'];
                        $row[$k]['ContainerHeight'] = $height;
                    }
    
                    self::storeRow($data,$row,$padding,$screenWidth);
                    if (count($data) == $line){
                        break;
                    }
    
                    //另起一行
                    list($screenWidth,$normalHeight,$maxHeight,$padding) = self::getLineOption(count($data) + 1,$normalOptions,$specialOptions);
                    $value['Width'.$maxHeight] = $value['Height'] > $maxHeight ? round($value['Width']*$maxHeight/$value['Height']) : $value['Width'];
                    $value['Width'.$normalHeight] = $value['Height'] > $normalHeight ? round($value['Width']*$normalHeight/$value['Height']) : $value['Width'];
    
                    $row = array($value);
                    $imgLengthNormal = $value['Width'.$normalHeight];
                    $imgLengthMax = $value['Width'.$maxHeight];
                } else {
                    //标准尺寸高缩小
                    array_push($row,$value);
                    $remainLength = $screenWidth - (count($row) -1)*$padding;
                    $imgLengthNormal += $value['Width'.$normalHeight];
                    $ratio = $remainLength/$imgLengthNormal;
                    $height = floor($normalHeight*$ratio);
                    foreach ($row as $k=>$v){
                        $row[$k]['TargetWidth'] = round($v['Width'.$normalHeight]*$ratio);
                        $row[$k]['TargetHeight'] = $v['Height'] > $height ? $height : $v['Height'];
                        $row[$k]['ContainerHeight'] = $height;
                    }
                     
                    self::storeRow($data,$row,$padding,$screenWidth);
                    if (count($data) == $line){
                        break;
                    }
    
                    $imgLengthNormal = $imgLengthMax = 0;
                    $row = array();
                }
            }
        }
        if ($data){
            $cutImage = \haibao\classlibrary\www\Config::getConfig(\haibao\classlibrary\www\Config::IMAGE_CUT_BASE_PATH);
            $uploads = \haibao\classlibrary\www\Config::getConfig(\haibao\classlibrary\www\Config::IMAGE_UPLOAD_BASE_PATH);
            $commonArticle = new \haibao\www\sites\common\Article();
            $picHost = \haibao\classlibrary\www\Config::getConfig(\haibao\classlibrary\www\Config::CLASSLIBRARY_CONFIG_HOST_PIC);
            foreach ($data as $row=>$images){
                $sumWidth = 0;
                foreach ($images as $key=>$image){
                    //采用round，宽可能有出入，将每行的最后一张图片缩放
                    $sumWidth += $image['TargetWidth'];
                    if ($key){
                        $sumWidth += $padding;
                    }
    
                    if ($key == count($images) - 1 && $sumWidth > $screenWidth){
                        $data[$row][$key]['TargetWidth'] -= $sumWidth - $screenWidth;
                    }
    
                    $count++;
                    array_push($ids,$image['Id']);
                    $fileName = $image['Filename'];
                    $isNewPic = true;
                    $isHasUploads = strpos($fileName, $uploads);
                    if ($isHasUploads === false){
                        $isNewPic = false;
                        $fileName = $cutImage.ltrim($fileName,'/');
                    } else {
                        $fileName = str_replace($uploads,$cutImage,$fileName);
                    }
    
                    $data[$row][$key]['ImageUrl'] = $commonArticle::getCutImageRealUrl($fileName, $isNewPic);
                    $data[$row][$key]['AccessUrl'] = $picHost.'/image/'.$image['Id'].'.html';
                    $data[$row][$key]['OriginUrl'] = \haibao\www\sites\common\Article::getImageRealUrl($image['Filename'],$image['Width'],$image['Height'],100,1);
                }
            }
        }
         
        return array($data,$count,$ids);
    }
    
    public static function getLineOption($line,$normalOptions,$specialOptions = array()){
        $screenWidth = $normalHeight = $maxHeight = $padding = 0;
        foreach ($normalOptions as $name=>$v){
            $$name = $v;
        }
         
        if ($specialOptions){
            foreach ($specialOptions as $options){
                if ($line == $options['lineNum']){
                    foreach ($options as $name=>$v){
                        if (isset($$name)){
                            $$name = $v;
                        }
                    }
    
                    break;
                }
            }
        }
         
        return array($screenWidth,$normalHeight,$maxHeight,$padding);
    }
     
    public static function storeRow(&$data,$row,$padding,$screenWidth){
        $sumWidth = $sumWidthRow = 0;
         
        //采用round可能会导致宽有误差，用最后一张图片弥补
        foreach ($row as $key=>$value){
            $sumWidthRow += $value['TargetWidth'];
            if ($key){
                $sumWidthRow += $padding;
                $sumWidth += $padding;
            }
             
            if ($key == count($row) - 1 && abs($sumWidthRow - $screenWidth) <5){
                $row[$key]['TargetWidth'] -= $sumWidthRow - $screenWidth;
            }
    
            $height = $row[$key]['TargetHeight'];
            $sumWidth += $row[$key]['TargetWidth'];
        }
         
        array_push($data,$row);
    }

} 